//
//  RegistUserViewController.m
//  PatientApp
//
//  Created by chirui on 2017/5/17.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "RegistUserViewController.h"
#import "RegistMessageViewController.h"

@interface RegistUserViewController ()<UIPickerViewDataSource, UIPickerViewDelegate>
{
    // 地区选择
    NSInteger _provinceIndex;   // 省份选择 记录
    NSInteger _cityIndex;       // 市选择 记录
    NSUInteger _areaIndex;      // 地区 记录
    
    NSString * provinceIdStr;  //省级代码
    NSString * cityIdStr;     //市级代码

}
@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIView *surePasswordView;
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *codeText;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@property (weak, nonatomic) IBOutlet UITextField *surePasswordYext;
@property (weak, nonatomic) IBOutlet UIButton *okBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@property (nonatomic,copy) NSString * typeStr;

@property (nonatomic, strong) UIPickerView * pickerView;
@property (nonatomic, strong) NSArray * arrayDS;
@property (weak, nonatomic) IBOutlet UITextField *areText;


@end

@implementation RegistUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationItem.titleView = [TopLabel withLabelWithLabelText:@"注册"];
    
    
    _typeStr = @"1";
    
    self.okBtn.selected = YES;
    self.sureBtn.layer.cornerRadius = 25.f;
    self.sureBtn.layer.masksToBounds = YES;
    
    NSString * path = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
    NSData *fileData = [NSData dataWithContentsOfFile:path];
    
    self.arrayDS = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableLeaves error:nil];

    
    _areText.inputView = self.pickerView;
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_return" target:self action:@selector(back)];
    
}
- (IBAction)backClick:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        //
    }];
}

//-(void)back{
//    
//    [self dismissViewControllerAnimated:YES completion:^{
//        //
//    }];
//    
////    [self.navigationController popViewControllerAnimated:YES];
//}

-(void)layerCornerRadiusView:(UIView *)view {
    
    view.layer.cornerRadius = 22.5f;
    view.layer.masksToBounds = YES;
    view.layer.borderWidth = 0.5;
    view.layer.borderColor = [UIColor grayColor].CGColor;
}

- (IBAction)codeBtnClick:(UIButton *)sender {
    
    if ([SHJudgeTools valiMobile:self.phoneText.text] != nil) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.yOffset = 100.f;
        hud.labelText = [SHJudgeTools valiMobile:self.phoneText.text];
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:0.5];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud removeFromSuperview];
        });
        return;
    }
    
    
    [self sendMSNetWorkingFor];
   
}
- (IBAction)okBtnClick:(UIButton *)sender {
    
    self.okBtn.selected = !self.okBtn.selected;
    
}
- (IBAction)userMessage:(UIButton *)sender {
    
    RegistMessageViewController * message =[[RegistMessageViewController alloc]init];
    [self presentViewController:message animated:YES completion:^{
        
    }];
    
}

- (IBAction)sureBtnClick:(UIButton *)sender {
    
    
    if ([SHJudgeTools valiMobile:self.phoneText.text] != nil) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.yOffset = 100.f;
        hud.labelText = [SHJudgeTools valiMobile:self.phoneText.text];
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:0.5];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud removeFromSuperview];
        });
        return;
    }else if (self.phoneText.text.length!=11) {
        
        [SHJudgeTools MBProgressHUDPromptWith:@"手机号码不正确" On:self.view];
        return;
        
    }else if (_areText.text.length<1){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"请选择区域" On:self.view];
        return;
        
    }else if(_codeText.text.length<1){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"验证码不能为空" On:self.view];
        return;
        
    }else if(_passwordText.text.length>8){
        [SHJudgeTools MBProgressHUDPromptWith:@"密码不能大于8位" On:self.view];
        return;
    }else if (![_passwordText.text isEqualToString:_surePasswordYext.text]){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"两次密码不一致" On:self.view];
        return;
        
    }else if ([_typeStr isEqualToString:@"0"]){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"请勾选同意用户协议" On:self.view];
        return;
        
    } else{
        
        [self registerNetWorking];
    }

}

-(void)initData
{
    _provinceIndex = _cityIndex =  0;
}

// 懒加载方式
-(UIPickerView *)pickerView

{
    if(!_pickerView){
        
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, HEIGHT - 216, WIDTH, 216)];
        _pickerView.dataSource = self;
        _pickerView.backgroundColor =[UIColor groupTableViewBackgroundColor];
        _pickerView.delegate = self;
        _pickerView.userInteractionEnabled =YES;
        
    }
    return _pickerView;
}

-(void)resetPickerSelectRow
{
    [self.pickerView selectRow:_provinceIndex inComponent:0 animated:YES];
    [self.pickerView selectRow:_cityIndex inComponent:1 animated:YES];
    [self.pickerView selectRow:_areaIndex inComponent:2 animated:YES];
    
}

#pragma mark - PickerView Delegate

// 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

// 每列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if(component == 0){
        
        
        return self.arrayDS.count;
    }
    else if (component == 1){
        return [self.arrayDS[_provinceIndex][@"sub"] count];
    }else {
        
        return [self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"] count];
    }
    
}

// 返回每一行的内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == 0){
        return self.arrayDS[row][@"area"];
    }
    else if (component == 1){
        return self.arrayDS[_provinceIndex][@"sub"][row][@"area"];
    }
    else{
        return self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][row][@"area"];
    }
}

// 滑动或点击选择，确认pickerView选中结果
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if(component == 0){
        _provinceIndex = row;
        _cityIndex = 0;
        _areaIndex = 0;
        [self.pickerView reloadComponent:1];
        [self.pickerView reloadComponent:2];
        
    }
    else if (component == 1){
        _cityIndex = row;
        _areaIndex = 0;
        
        [self.pickerView reloadComponent:2];
    }
    else{
        
        _areaIndex = row;
        
    }
    // 重置当前选中项
    [self resetPickerSelectRow];
   NSString *    address = [NSString stringWithFormat:@"%@ %@ %@", self.arrayDS[_provinceIndex][@"area"], self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"area"],self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][_areaIndex][@"area"]];
    _areText.text = address;
    
}


#pragma mark  网络请求


-(void)registerNetWorking {
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,regin_api];
    NSString * areaStr = [_areText.text stringByReplacingOccurrencesOfString:@" " withString:@"|"];
    NSString * md5Password = [SHJudgeTools md532BitLower:_passwordText.text];
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",_phoneText.text]];
    
    NSDictionary * dic = @{@"uphone":_phoneText.text,
                           @"upasswords":md5Password,
                           @"smscode":[SHJudgeTools md532BitLower:_codeText.text],
                           @"area":areaStr,
                           @"ver":md5ver
                           };
    
     [MBProgressHUD showMessag:@"正在注册..." withDelay:0 toView:self.view withMode:MBProgressHUDModeIndeterminate hideWithDelay:0];
    [PostNetWorking postNetWorkingStr:parametersStr andparameters:dic Success:^(id responseObject) {
      [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"err"] intValue]==0) {
            
            [MBProgressHUD showMessag:@"注册成功" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
            });
            
        } else {
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
        
    } failed:^(NSError *error) {
        NSLog(@"ERROR ==%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showMessag:@"网络错误" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
    }];
    
}

// 验证码
-(void)sendMSNetWorkingFor{
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",_phoneText.text]];
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@",address_url,regin_sms_api,_phoneText.text,md5ver];
   
    NSLog(@"parametersStr = %@",parametersStr);
    SHuiMBhubNoTimeStr(@"正在发送");
    [PostNetWorking netWorkingStr:parametersStr  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"err"] intValue]==0) {
            SHuiMBhudTextTimeStr(@"发送成功");
            
            __block int timeout = 60; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=1){
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self.codeBtn setTitle:@"获取" forState:UIControlStateNormal];
                        self.codeBtn.userInteractionEnabled = YES;
                    });
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        NSString  * time = [NSString stringWithFormat:@"%d(秒)",timeout];
                        [UIView beginAnimations:nil context:nil];
                        [UIView setAnimationDuration:1];
                        [self.codeBtn setTitle:time forState:UIControlStateNormal];
                        [UIView commitAnimations];
                        self.codeBtn.userInteractionEnabled = NO;
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);

        } else {
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
   
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
